package com.twotiger.and.activity;

import java.util.HashMap;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import app.twotiger.p2p.R;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.ImageBean;
import com.twotiger.and.bean.ImageList;
import com.twotiger.and.util.CacheUtils;
import com.twotiger.and.util.DownPicUtil;
import com.twotiger.and.util.ListUtils;
import com.twotiger.and.util.NetWorkUtil;
import com.twotiger.and.util.PackageUtils;
import com.twotiger.and.util.PreferencesUtils;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.ViewUtils;

/**
 * 启动界面
 * @Description:
 * @Author douxy
 * @Date 2015年8月12日 下午4:45:59
 */
public class MainActivity extends BaseActivity {

    public static String IMGLIST = "imageList";

    private HashMap<String, String> parm;
    protected static final int GETBOOTIMAGSUCCESS = 0;
    private static final int GETBOOTIMAGFAILURE = 1;

    private Bitmap image; //要展示的图片
    private ImageView v;
    private Bitmap cacheBitmap;

    private List<ImageBean> img_list;

    @Override
    protected void processLogic() {
        parm = getParm();

        setGestureEnable(false);
        if (application.otherService.isUpgrade(this)) {// 判断版本升级了,就打开引导页
            PreferencesUtils.putString(mContext, application.otherService.sp_versionname,
                PackageUtils.getAppVersionName(this)); //将当前版本号存到sp中
            Intent intent = new Intent(MainActivity.this, GuideActivity.class);
            startNewActivity(intent, R.anim.fade_in_anim, R.anim.fade_out_anim, true);
        } else {
            //将上次缓存的图片取出来
            cacheBitmap = CacheUtils.getBitmapFormSDCard();
            //将上次缓存的img list取出来
            String imgListString = PreferencesUtils.getString(mContext, IMGLIST);
            img_list = JSON.parseArray(imgListString, ImageBean.class);
            startGo();
        }
        if (NetWorkUtil.isNetworkConnected(mContext)) {
            getConstantData(false);
        } 
    }

    private void startGo() {

        if (cacheBitmap != null) {
            v.setBackgroundDrawable(new BitmapDrawable(cacheBitmap));
        } else {
            v.setBackgroundResource(R.drawable.splash_image);
        }
        start(false);
        if (!NetWorkUtil.isNetworkConnected(mContext)) {

        } else {
            requestImage();
        }
    }

    class DownImageTask extends AsyncTask<String, Integer, Boolean> {

        @Override
        protected Boolean doInBackground(String... params) {
            image = DownPicUtil.getNetWorkBitmap(params[0]);
            return true;
        }

        // 下载完成回调
        @Override
        protected void onPostExecute(Boolean result) {
            //将图片缓存到sd卡，供下次使用
            if (image != null) { //不为空的时候才会去覆盖sd卡目录的图片
                CacheUtils.cacheBitmapToSDCard(image);
                if (v != null) {
                    v.setBackgroundDrawable(new BitmapDrawable(image));
                }
            }
            super.onPostExecute(result);
        }

        // 更新进度回调
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
        }

    }

    @Override
    protected void onPause() {
        JPushInterface.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        JPushInterface.onResume(this);
        super.onResume();
    }

    @Override
    protected void setListener() {

        v.setOnClickListener(this);

        handler = new BaseHandler(this) {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                case GETBOOTIMAGSUCCESS:
                    Basebean result = JSON.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) { //有新图片来展示
                        ImageList imageList = JSON.parseObject(result.data, ImageList.class);
                        List<ImageBean> list = JSON
                            .parseArray(imageList.getList(), ImageBean.class);
                        if (!ListUtils.isEmpty(list)) {
                            PreferencesUtils.putString(MainActivity.this, IMGLIST,
                                imageList.getList()); //将本地数据存储，方便下次点击跳转链接
                            new DownImageTask().execute(Constants.HOST + list.get(0).getPicUrl()); //下载图片 并保存至sd卡
                        }
                    }
                    break;
                case GETBOOTIMAGFAILURE:
                    break;

                default:
                    break;
                }
            }
        };
    }

    private void requestImage() {
        parm.clear();
        parm.put("type", "bootPage"); //启动页类型请求
        getDate(parm, Constants.IMGQUERY, handler, GETBOOTIMAGSUCCESS, GETBOOTIMAGFAILURE, false,
            true, false);
    }

    private void start(boolean hasNewPic) {

        AlphaAnimation aa = new AlphaAnimation(0.5f, 1f);
        aa.setDuration(2000);

        if (hasNewPic) { //从网上下载到了最新图片
            v.setBackgroundDrawable(new BitmapDrawable(image));
        } else {
            if (cacheBitmap != null) {
                v.setBackgroundDrawable(new BitmapDrawable(cacheBitmap));
            } else {
                v.setBackgroundResource(R.drawable.splash_image);
            }
        }
        v.startAnimation(aa);
        aa.setAnimationListener(new AnimationListener() {
            public void onAnimationStart(Animation animation) {
            }

            public void onAnimationEnd(Animation animation) {
                Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                intent.putExtra("PUSH", getIntent().getSerializableExtra("PUSH"));
                /*
                 * 手势校验移交给各自activity or fragment 负责
                 * 
                 * if (needValidGesture()) {
                   intent.setClass(MainActivity.this, LockActivity.class);
                   }
                 */
                startNewActivity(intent, R.anim.fade_in_anim, R.anim.fade_out_anim, true);
            }

            @Override
            public void onAnimationRepeat(Animation arg0) {

            }
        });
    }

    @Override
    protected void findViewById(View view) {
        v = (ImageView) this.findViewById(R.id.splash_image); //先让图片显示出来，防止网络过慢的时候，没东西显示
    }

    @Override
    protected void onBackPress() {

    }

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        return inflater.inflate(R.layout.splash_activity, null);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
        case R.id.splash_image:
            if (ViewUtils.isFastDoubleClick(view)) {
                return;
            }
            if (ListUtils.isEmpty(img_list) || StringUtils.isEmpty(img_list.get(0).getUrl())) {
                return;
            }
            Intent intent = new Intent(MainActivity.this, WebViewPage.class);
            intent.putExtra("url", img_list.get(0).getUrl());
            intent.putExtra("title", img_list.get(0).getName());
            intent.putExtra("BACK_MODE", WebViewPage.BACK_TO_HOME); //webview的返回形式
            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, true);
            break;
        default:
            break;
        }
    }

}
